import Vue from 'vue';
import COS from 'cos-js-sdk-v5';
import { getQueryVariable, getShareCode } from '@/utils';
import { COS_BIZ_TYPE } from '@/constants';
import { describeStorageCredential } from '@/api/modules/auth.js';

export const cos = {
  cosInstance: null,
  cosTimeout: 5000,
  config: {
    Bucket: '',
    Region: '',
    Prefix: '',
    botBizId: '',
    bizType: ''
  },
  async getCos(bizType, isPublic = false, fileType = undefined, ignoreTypeKey,fileData) {
    // console.log(fileData,'filefilefilefile')
    const botBizId = window.localStorage.getItem("bot_biz_id_im");
    /**
     * 后台对无应用id的场景加了特殊逻辑，使用id 0请求可以获取临时token
     * 但是返回的file_path为空，不可使用，因此限定场景为头像上传，使用public path
     */
    const DefaultCosReqData = {
      botBizId,
      isPublic,
    };
    // 获取下载、预览链接时，需要过滤fileType和typeKey，避免权限问题
    if (fileType) {
      DefaultCosReqData.fileType = fileType;
    }
    if (!ignoreTypeKey) {
      DefaultCosReqData.typeKey = 'realtime';
    }
    try {
      const formData = new FormData();
      formData.append('file', fileData); 
      formData.append('botBizId', DefaultCosReqData.botBizId); 
      formData.append('fileType', DefaultCosReqData.fileType); 
      formData.append('isPublic', DefaultCosReqData.isPublic); 
      formData.append('typeKey', DefaultCosReqData.typeKey); 
      // 直接获取cos信息，初始化cos实例
      const tempConfig = await describeStorageCredential(formData);

      if (tempConfig.status == 200) {
        const resdata = tempConfig.data;
        const url = `${window.location.protocol}//${resdata.Location}`
        const ETag = resdata.ETag
        return {
          url:url,
          e_tag:ETag,
          cos_url:resdata.UploadPath,
          Bucket:resdata.Bucket,
          cosHash:resdata.cosHash,
        };
      }
    } catch (e) {
      Vue.prototype.$message.error("获取COS信息失败");
      Vue.prototype.$message.error("下载初始化失败");
      console.log("下载初始化失败error", e);
    }
  },
  async upload(isPublic, bizType, files, onProgress, onUploaded, ignoreTypeKey) {
    return new Promise((resolve, reject) => {
      files.forEach((file) => {
        const nameArr = (file.name || file.saveName).split(".");
        
        this.getCos(bizType, isPublic, nameArr[nameArr.length - 1], ignoreTypeKey,file.data).then(
          (instance) => {
            console.log(instance, 'instanceinstanceinstance')
            if (!instance) {
              reject("cos上传出错");
            }else{
              onProgress && onProgress(file.saveName, {
                ...file,
                cos_url: instance.cos_url,
                process: 1 - 0.01,
              });
              setTimeout(()=>{
                onProgress && onProgress(file.saveName, {
                  ...file,
                  process: 1,
                  e_tag: instance.e_tag,
                  cos_url: instance.cos_url,
                  cos_hash: instance.e_tag,
                  size: file.data.size || 0,
                  url: instance.url,
                  cos_bucket:instance.Bucket,
                  cos_hash:instance.cosHash,
                });
              },100)
              resolve({
                ...file,
                saveName: file.saveName,
                e_tag: instance.e_tag,
                cos_url: instance.cos_url,
                cos_hash: instance.e_tag,
                size: file.data.size || 0,
                url: instance.url,
                cos_bucket:instance.Bucket,
                cos_hash:instance.cosHash,
              });
            }
          }
        );
      });
    });
  },
  async getDocHtmlUrl(bizType, file) {
    try {
      const nameArr = (file.name || file.saveName).split(".");
      const fileType = nameArr[nameArr.length - 1];
      const cos = await this.getCos(bizType, false, null, true);

      const data = await new Promise((resolve, reject) => {
        cos.getObjectUrl({
          Bucket: this.config.Bucket,
          Region: this.config.Region,
          Key: file.cos_url,
          Query: {
            'ci-process': 'doc-preview', /* 必须，数据万象处理能力，文档预览固定为 doc-preview */
            dstType: 'html',
          },
        }, function (err, data) {
          if (err) {
            reject(err);
          } else {
            resolve(data);
          }
        });
      });
      return data.Url;
    } catch (err) {
      console.error('Failed to get document HTML URL:', err);
      throw err;
    }
  },

  async getDownloadUrl(bizType, file, cb, expires) {
    try {
      const nameArr = (file.name || file.saveName).split(".");
      const fileType = nameArr[nameArr.length - 1];
      const instance = await this.getCos(bizType, false, null, 1, true);
      const data = await new Promise((resolve, reject) => {
        const params = {
          Bucket: this.config.Bucket,
          Region: this.config.Region,
          Key: file.cos_url,
          Sign: true,
        };
        if (expires) {
          params.Expires = expires;
        }
        instance.getObjectUrl(
          params,
          function (err, data) {
            if (err) {
              reject(err);
              return;
            }
            resolve(data);
          }
        );
      });
      return data.Url +
        (data.Url.indexOf("?") > -1 ? "&" : "?") +
        "response-content-disposition=attachment&response-content-type=application%2Foctet-stream";
    } catch (err) {
      cb && cb(err);
      throw err;
    }
  },
  reNameFile(length) {
    const data = [
      "0",
      "1",
      "2",
      "3",
      "4",
      "5",
      "6",
      "7",
      "8",
      "9",
      "A",
      "B",
      "C",
      "D",
      "E",
      "F",
      "G",
      "H",
      "I",
      "J",
      "K",
      "L",
      "M",
      "N",
      "O",
      "P",
      "Q",
      "R",
      "S",
      "T",
      "U",
      "V",
      "W",
      "X",
      "Y",
      "Z",
      "a",
      "b",
      "c",
      "d",
      "e",
      "f",
      "g",
      "h",
      "i",
      "j",
      "k",
      "l",
      "m",
      "n",
      "o",
      "p",
      "q",
      "r",
      "s",
      "t",
      "u",
      "v",
      "w",
      "x",
      "y",
      "z",
    ];
    let nums = "";
    for (let i = 0; i < length; i++) {
      const r = parseInt(Math.random() * 61, 10);
      nums += data[r];
    }
    return nums + "-" + parseInt(Math.random() * 10000000000, 10);
  },
};
